<template>
  <div class="proKnow">
    <div class="leftTitle">专业知识</div>
    <div class="rightContent">
      <div class="chartContainer">
        <div id="chartElement" ref="chartElement"></div>
      </div>
      <div class="otherInfo">
        <div class="currentAna" :ref="`containerBlock`">
          <div class="currentAnaTitle">阶段知识分析</div>
          <div class="currentAnaContent">
            <div v-html="resDataForAna" :ref="`contentBlock`"></div>
          </div>
          <el-popover
            v-if="showExpandFourth"
            placement="top"
            width="700"
            trigger="click"
          >
            <div v-html="resDataForAna"></div>
            <span slot="reference" class="expand-btn">
              <span class="dot">...</span>
              展开
            </span>
          </el-popover>
        </div>
        <div class="recomBook">
          <div class="recomBookTitle">推荐书籍</div>
          <div class="recomBookContent">
            <div
              class="bookItem"
              v-for="(item, index) in resDataForBook"
              :key="index"
            >
              <p class="bookInfo">
                <span class="bookName">《{{ item.name }}》</span>
                <span class="bookAuthor">作者：{{ item.author }}</span>
              </p>
              <p class="bookLink">
                <a :href="item.url" target="_blank" rel="noopener noreferrer">{{
                  item.url
                }}</a>
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getLayerAssemblyData } from "@/api/position-detail.js";
export default {
  name: "professionKnow",
  data() {
    return {
      showExpandFourth: false,
      myChart: null,
      chartSeries: [],
      chartIndicator: [],
      chartLegend: [],
      indicatorValueColor: "#54D47C",
      selectedLevel: "入门",
      resDataForchat: {},
      resDataForAna: "暂无",
      resDataForBook: [],
    };
  },
  mounted() {
    this.reqGetLayerAssemblyData();
  },
  methods: {
    reqGetLayerAssemblyData() {
      getLayerAssemblyData({
        positionId: this.$route.query.id,
        layerIds: 206, //209等级证书，206专业知识 207专业技能，208能力素质
        hide: 2,
      }).then((res) => {
        if (res.code === 200) {
          // console.log("-------------->专业知识数据：", res.data);
          const resData = res.data[0];
          const layerValue = resData.layerValue;
          this.resDataForchat = layerValue["专业知识"] || {};
          //阶段知识分析需要换行
          layerValue["阶段知识分析"] = layerValue["阶段知识分析"].replace(
            /\r\n|\n/g,
            "<br />"
          );
          this.resDataForAna = layerValue["阶段知识分析"] || "暂无";
          this.resDataForBook = layerValue["推荐书籍"] || "暂无";
          // console.log("resDataForchat", resDataForchat);
          this.handleData(this.resDataForchat);
          this.checkOverflow();
        }
      });
    },
    initChart() {
      if (!this.$refs["chartElement"]) return;
      if (this.myChart) {
        this.myChart.dispose();
      }
      this.myChart = this.$echarts.init(this.$refs["chartElement"]);
      let indicator = this.chartIndicator;
      let series = this.chartSeries;
      // console.log("indicator", indicator);
      // console.log("series", series);
      const that = this;
      if (!indicator.length) {
        return;
      }
      const selectedStatus = {};
      this.chartLegend.forEach((item) => {
        if(this.selectedLevel == item.name) {
          selectedStatus[item.name] = true;
        }else{
          selectedStatus[item.name] = false;
        }
      });
      // console.log("------------->selectedStatus", selectedStatus);
      let option = {
        legend: {
          data: this.chartLegend,
          selected: selectedStatus,
          left: 20,
          itemGap: 18,
          align: "left",
          itemWidth: 8,
          itemHeight: 8,
          textStyle: {
            color: "#8193B2",
            fontSize: 14,
            lineHeight: 12,
            rich: {
              a: {
                // 没有设置 `lineHeight`，则 `lineHeight` 为 56,选中字体颜色
                color: "#222",
                fontSize: 18,
                fontWeight: 600,
              },
              b: {
                // 没有设置 `lineHeight`，则 `lineHeight` 为 56,未选中字体颜色
                color: "#666",
                fontSize: 14,
                // fontWeight: 600,
              },
            },
          },
          formatter: function (name) {
            if (name == that.selectedLevel) {
              return `{a|${name}}`;
            } else {
              return `{b|${name}}`;
            }
          },
        },
        radar: [
          {
            indicator,
            radius: "40%",
            center: ["50%", "55%"],
            // splitNumber: 4,
            triggerEvent: true,
            nameGap: 14,
            axisName: {
              formatter: (value, indicator) => {
                const name = indicator.name;
                const realValue = indicator.value;
                const parts = name.split("");
                let formattedName = "";
                let charLength = 0;
                for (let i = 0; i < parts.length; i++) {
                  charLength += this.checkCharLength(parts[i]);
                  if (charLength >= 10) {
                    formattedName += "\n" + parts[i];
                    charLength = 0;
                  } else {
                    formattedName += parts[i];
                  }
                }
                return `{a|${formattedName}}\n{b|${realValue}}`;
              },
              rich: {
                a: {
                  color: "#555",
                  fontSize: 14,
                  lineHeight: 16,
                  align: "left",
                },
                b: {
                  fontFamily: "D-DIN-PRO-500-Medium",
                  fontWidth: "bold",
                  color: this.indicatorValueColor,
                  fontSize: 26,
                  padding: [0, 0, 0, 6],
                },
              },
              textStyle: {
                color: "#fff",
              },
            },
            axisLine: {
              lineStyle: {
                color: "#B8D6FD",
                width: 0.5,
              },
            },
            splitLine: {
              lineStyle: {
                color: [
                  "#E5EEF7",
                  "#E5EEF7",
                  "#E5EEF7",
                  "#E5EEF7",
                  "#E5EEF7",
                  "#B8D4F2",
                ],
              },
            },
          },
        ],
        // series: series,
        // 修改series生成逻辑
        series: this.chartSeries.map((item, index) => ({
          ...item,
          show: index === 0, // 仅第一项默认显示
          lazyLoad: index !== 0, // 非首项标记为延迟加载
        })),
      };

      try {
        option && this.myChart.setOption(option);
      } catch (error) {
        console.log("表格报错erro", error);
      }
      window.addEventListener("resize", () => {
        if (this.myChart) {
          this.myChart.resize();
        }
      });
      this.myChart.on("click", this.handleMyChartClick);
    },

    checkCharLength(char) {
      if (char.match(/[\u4e00-\u9fa5\u3000-\u303f\uff00-\uffef]/)) {
        return 1;
      } else {
        return 0.5; // 英文字符宽度为0.5
      }
    },
    handleData(data) {
      //循环处理每一个等级（入门、初级什么的）
      //声明series（数据的集合）,后续直接放到options里
      const series = [];
      const legend = [];
      for (const levelName in data) {
        if (Object.hasOwnProperty.call(data, levelName)) {
          const levelvalue = data[levelName];
          legend.push({
            name: levelName,
            icon: "circle",
            itemStyle: { color: this.getColor(levelName) },
          });
          const value = [];
          //提取每一项知识的值
          for (const key in levelvalue) {
            if (Object.hasOwnProperty.call(levelvalue, key)) {
              const score = levelvalue[key];
              value.push(score);
            }
          }
          //拼接最终的数据
          const obj = {
            type: "radar",
            name: levelName,
            emphasis: {
              lineStyle: {
                width: 4,
              },
            },
            data: [
              {
                value,
                itemStyle: {
                  // 设置连接线不可见
                  opacity: levelName == this.selectedLevel ? 1 : 0,
                  color: this.getColor(levelName),
                  shadowColor: "#a1c7f9",
                  shadowBlur: levelName == this.selectedLevel ? 10 : 0,
                  borderWidth: "2",
                  borderColor: "#FFF",
                },
                lineStyle: {
                  color: this.getColor(levelName),
                  shadowColor: "#a1c7f9",
                  shadowBlur: levelName == this.selectedLevel ? 10 : 0,
                },
              },
            ],
          };
          // console.log("obj", obj);

          //拼完后放入series中
          series.push(obj);
        }
      }
      //处理indicator(名字)，因为不想写的太冗余，所以额外写了
      const indicator = [];
      //selectedLevel可能因为点中不同的series可改变，默认是“入门”
      const firstItem = data[this.selectedLevel];
      for (const indicatorName in firstItem) {
        if (Object.hasOwnProperty.call(firstItem, indicatorName)) {
          const element = firstItem[indicatorName];
          indicator.push({ name: indicatorName, max: 5, value: element });
        }
      }
      //最后赋值
      this.chartSeries = series;
      this.chartIndicator = indicator;
      this.chartLegend = legend;
      console.log("------------->最后的数据：", indicator, series, legend);

      this.$nextTick(() => {
        this.initChart();
      });
    },
    getColor(levelName) {
      const colors = {
        入门: "#54D47C",
        初级: "#3698FF",
        中级: "#AD6DFF",
        高级: "#FF88D4",
      };
      return colors[levelName] || "#4283FF";
    },
    handleMyChartClick(params) {
      console.log("--------handleMyChartClick-------->params", params);
      if (!params.seriesName) {
        return;
      }
      this.indicatorValueColor = this.getColor(params.seriesName);
      this.selectedLevel = params.seriesName;
      this.myChart.off("click", this.handleMyChartClick);
      this.$nextTick(() => {
        this.handleData(this.resDataForchat);
      });
    },
    checkOverflow(index) {
      this.$nextTick(() => {
        // 这部分是secondBlock的逻辑
        const content = this.$refs[`contentBlock`];
        const container = this.$refs[`containerBlock`];

        // console.log("content", content);
        // console.log("container", container);
        if (!content || !container) {
          return;
        }

        const contentHeight = content.scrollHeight;
        const containerHeight = container.clientHeight;

        if (contentHeight > containerHeight - 30) {
          this.showExpandFourth = true;
        } else {
          this.showExpandFourth = false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped></style>
